package com.aibaixun.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import com.aibaixun.common.constant.Constants;
import com.aibaixun.common.core.domain.R;
import com.aibaixun.common.exception.ServiceException;
import com.aibaixun.common.utils.BeanCopyUtils;
import com.aibaixun.common.utils.TreeBuildUtils;
import com.aibaixun.system.domain.*;
import com.aibaixun.system.domain.dto.BindDeviceDto;
import com.aibaixun.system.domain.vo.QueryDeviceTreeVo;
import com.aibaixun.system.domain.vo.QueryDeviceVo;
import com.aibaixun.system.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aibaixun.system.mapper.DicmAddressMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author zhangyh
* @description 针对表【dicm_address(地址信息表)】的数据库操作Service实现
* @createDate 2023-09-14 10:17:45
*/
@Service
public class DicmAddressServiceImpl extends ServiceImpl<DicmAddressMapper, DicmAddress>
    implements DicmAddressService{

    @Autowired
    private PostureDeviceService postureDeviceService;

    @Autowired
    private DicmNvrService dicmNvrService;

    @Autowired
    private DicmDeviceService dicmDeviceService;

    @Autowired
    private DicmCabinetService dicmCabinetService;

    @Autowired
    private DicmSignalhService dicmSignalhService;


    @Override
    public R<List<Tree<String>>> getTree(DicmAddress dto) {
        List<QueryDeviceTreeVo> addressList = baseMapper.queryAddressList(dto);
//        if(dto.getDataType() == null){
//            List<QueryDeviceTreeVo> cabinetList = dicmCabinetService.queryCabinetList();
//            if (CollectionUtil.isNotEmpty(cabinetList)){
//                addressList.addAll(cabinetList);
//            }
//            List<QueryDeviceTreeVo> deviceList = dicmDeviceService.queryDeviceAll();
//            if (CollectionUtil.isNotEmpty(deviceList)){
//                addressList.addAll(deviceList);
//            }
////            List<QueryDeviceTreeVo> deviceServiceList = postureDeviceService.queryDeviceList();
////            if (CollectionUtil.isNotEmpty(deviceServiceList)){
////                addressList.addAll(deviceServiceList);
////            }
//            List<QueryDeviceTreeVo> nvrList = dicmNvrService.queryNvrTreeList();
//            if (CollectionUtil.isNotEmpty(nvrList)){
//                nvrList.forEach(item -> {
//                    String nvrDetailUrl = dicmNvrService.getNvrDetailUrl(item.getAddressId());
//                    if (StringUtils.isNotEmpty(nvrDetailUrl)){
//                        item.setRtspUrl(nvrDetailUrl);
//                    }
//                });
//                addressList.addAll(nvrList);
//            }
//        }else if(dto.getDataType().intValue() == 3){
//            List<QueryDeviceTreeVo> cabinetList = dicmCabinetService.queryCabinetList();
//            if (CollectionUtil.isNotEmpty(cabinetList)){
//                addressList.addAll(cabinetList);
//            }
//        }
        if(dto.getDataType() != null && dto.getDataType().intValue() == 3) {
            List<QueryDeviceTreeVo> cabinetList = dicmCabinetService.queryCabinetList(null);
            if (CollectionUtil.isNotEmpty(cabinetList)) {
                addressList.addAll(cabinetList);
            }
        }

        return R.ok(buildDeptTreeSelect(addressList));
    }

    @Override
    public R queryDeviceByRoomId(String parentId) {
        List<QueryDeviceTreeVo> addressList = new ArrayList();
        List<QueryDeviceTreeVo> cabinetList = dicmCabinetService.queryCabinetList(parentId);
            if (CollectionUtil.isNotEmpty(cabinetList)){
                addressList.addAll(cabinetList);
            }
            List<QueryDeviceTreeVo> deviceList = dicmDeviceService.queryDeviceAll(parentId);
            if (CollectionUtil.isNotEmpty(deviceList)){
                addressList.addAll(deviceList);
            }
            List<QueryDeviceTreeVo> nvrList = dicmNvrService.queryNvrTreeList(parentId);
            if (CollectionUtil.isNotEmpty(nvrList)){
                nvrList.forEach(item -> {
                    String nvrDetailUrl = dicmNvrService.getNvrDetailUrl(item.getAddressId());
                    if (StringUtils.isNotEmpty(nvrDetailUrl)){
                        item.setRtspUrl(nvrDetailUrl);
                    }
                });
                addressList.addAll(nvrList);
            }
        return R.ok(buildDeptTreeSelect(addressList));
    }

    @Override
    public QueryDeviceVo queryByRoomId(String cabinetId) {
        QueryDeviceVo vo = dicmCabinetService.queryByRoomUeId(cabinetId);
        if (null != vo){
            return vo;
        }
        QueryDeviceVo returnVo = dicmDeviceService.queryByRoomUeId(cabinetId);
        if (returnVo != null){
            List<DicmSignalh> dicmSignalhList = dicmSignalhService.queryDicmSignalhByDeviceId(returnVo.getDeviceId());
            returnVo.setDicmSignalhList(dicmSignalhList);
            return returnVo;
        }
        return null;
    }

    @Override
    public List<String> queryAddressIdList() {
        List<String> addressIdList = baseMapper.queryAddressIdList();
        return addressIdList;
    }

    @Override
    public void addDicmAddress(List<DicmAddress> dicmAddressesList) {
        if (CollectionUtil.isNotEmpty(dicmAddressesList)){
            dicmAddressesList.forEach(item -> {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("address_id",item.getAddressId());
                DicmAddress dicmAddress = baseMapper.selectOne(queryWrapper);
                if (null != dicmAddress){
                    baseMapper.updateById(item);
                }else {
                    baseMapper.insert(item);
                }

            });
        }

    }

    @Override
    @Transactional
    public R bindDeviceUe(BindDeviceDto dto) {
        if (dto.getType().equals("1")){
            if (StringUtils.isNotEmpty(dto.getUeId())) {
                Long count = this.baseMapper.selectCount(
                    new LambdaQueryWrapper<DicmAddress>()
                        .eq(DicmAddress::getUeId, dto.getUeId())
                );
                if (count > 0) {
                    return R.fail("ueId已存在");
                }
            }
            LambdaUpdateWrapper<DicmAddress> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.eq(DicmAddress::getAddressId,dto.getId());
            updateWrapper.set(DicmAddress::getUeId,dto.getUeId());
            this.baseMapper.update(null, updateWrapper);
            if (StringUtils.isNotEmpty(dto.getUeId()) && dto.isRefreshStatus()){
                dicmDeviceService.updateDeviceUeId(dto);
                dicmCabinetService.updateCabinetUeId(dto);
                dicmNvrService.updatenvrUeId(dto);
            }
        }else if (dto.getType().equals("2")){
            if (StringUtils.isNotEmpty(dto.getUeId())) {
                Long count = baseMapper.countPostureDevice(dto.getUeId());
                if (count > 0) {
                    return R.fail("ueId已存在");
                }
            }
            postureDeviceService.updateDeviceById(dto);
        }else if (dto.getType().equals("3")){
            if (StringUtils.isNotEmpty(dto.getUeId())) {
                Long count = baseMapper.countDicmNvr(dto.getUeId());
                if (count > 0) {
                    return R.fail("ueId已存在");
                }
            }
            dicmNvrService.updateNvr(dto);
        }else if ("4".equals(dto.getType())){
            if (StringUtils.isNotEmpty(dto.getUeId())) {
                Long count = baseMapper.countDicmDevice(dto.getUeId());
                if (count > 0) {
                    return R.fail("ueId已存在");
                }
            }
            dicmDeviceService.updateDevice(dto);
        }else if ("5".equals(dto.getType())){
            if (StringUtils.isNotEmpty(dto.getUeId())) {
                Long count = baseMapper.countDicmCabinet(dto.getUeId());
                if (count > 0) {
                    return R.fail("ueId已存在");
                }
            }
            dicmCabinetService.updateCabinet(dto);
        }
        return R.ok();
    }

    @Override
    public void resetUeId() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ue_id","空");
        List<DicmAddress> addressList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(addressList)){
            addressList.forEach(item -> {
                item.setUeId("");
                baseMapper.updateById(item);
            });
        }
        dicmCabinetService.resetUeId();
        dicmDeviceService.resetUeId();
        dicmNvrService.resetUeId();
        postureDeviceService.resetUeId();
    }

    @Override
    public DicmAddress queryCabinetByName(String item) {
        return null;
    }

    @Override
    public void saveDicmAddress(List<DicmAddress> addressesList) {
        addressesList.forEach(item -> {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("address_id",item.getAddressId());
            DicmAddress dicmAddress = baseMapper.selectOne(queryWrapper);
            if (null == dicmAddress){
                baseMapper.insert(item);
            }
        });
    }

    @Override
    public List<DicmAddress> queryAddressaIdByAddressId(String addressId) {
        return baseMapper.queryAddressaIdByAddressId(addressId);
    }

    public List<Tree<String>> buildDeptTreeSelect(List<QueryDeviceTreeVo> addressList) {
        if (CollUtil.isEmpty(addressList)) {
            return CollUtil.newArrayList();
        }
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setNameKey("addressName");


        //构建树
        List<Tree<String>> treeNodes = TreeUtil.build(addressList,addressList.get(0).getParentId(), treeNodeConfig, (treeNode, tree) -> {
            tree.setId(treeNode.getAddressId());
            if (treeNode.getAddressId().equals("5530")){
                System.out.println(treeNode.getAddressName());
            }
            tree.setParentId(treeNode.getParentId());
            tree.setName(treeNode.getAddressName());
            // 设置自定义属性
            tree.putExtra("addressType", treeNode.getAddressType());
            tree.putExtra("addressId", treeNode.getAddressId());
            tree.putExtra("ueId", treeNode.getUeId());
            tree.putExtra("location", treeNode.getLocation());
            tree.putExtra("wmfNo", treeNode.getWmfNo());
            tree.putExtra("height", treeNode.getHeight());
            tree.putExtra("type", treeNode.getType());
            tree.putExtra("rtspUrl",treeNode.getRtspUrl());
        });
        return treeNodes;

//        return TreeBuildUtils.build(addressList, (address, tree) -> {
//            tree.setId(address.getAddressId());
//            tree.setParentId(address.getParentId());
//            tree.setName(address.getAddressName());
//            tree.putExtra("addressType",address.getAddressType());
//            tree.putExtra("ueId",address.getUeId());
//        });
    }
}




